package com.example.littleken.appmanager.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;

import com.example.littleken.appmanager.entity.AppInfo;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by littleken on 2018/4/21.
 * 工具类
 */

public class Utils {

    public static List<AppInfo> getAppList(Context context) {
        //返回值集合
        List<AppInfo> list = new ArrayList<AppInfo>();
        //实例化包管理器
        PackageManager pm = context.getPackageManager();
        //获取所有已经安装的应用信息
        List<PackageInfo> pList = pm.getInstalledPackages(0);
        //遍历集合
        for (int i = 0; i < pList.size(); i++) {
            PackageInfo packageinfo = pList.get(i);//拿到每个packageinfo
            if (inThirdPartyApp(packageinfo.applicationInfo) && //去除掉系统应用和本应用
                     !packageinfo.packageName.equals(context.getPackageName())) {//通过比较包名去掉本应用
                AppInfo app = new AppInfo();
                //填充实体类
                app.packageName = packageinfo.packageName;//获取对应app信息
                app.versionName = packageinfo.versionName;
                app.versionCode = packageinfo.versionCode;
                app.insTime = packageinfo.firstInstallTime;
                app.updTime = packageinfo.lastUpdateTime;
                //获取应用名
                app.appName = (String) packageinfo.applicationInfo.loadLabel(pm);//通过applicationInfo实体类属性反射出应用名
                //获取图标
                app.icon = packageinfo.applicationInfo.loadIcon(pm);
                //计算程序大小
                String dir = packageinfo.applicationInfo.publicSourceDir;
                //通过file把dir实例化成一个对象，再计算其大小
                long byteSize = new File(dir).length();
                //处理成以“M”为单位
                app.byteSize = byteSize;//实际大小
                app.size = getSize(byteSize);//格式化之后大小
                //添加到集合
                list.add(app);
            }
        }
        return list;
    }

    public static boolean inThirdPartyApp(ApplicationInfo appInfo) {//判断是否为系统应用
        boolean flag = false;
        if ((appInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {//系统可更新应用
            flag = true;
        } else if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {//系统应用
            flag = true;
        }
        return flag;
    }

    public static String getSize(long size) {//把文件大小从比特处理成以“M”为单位
        return new DecimalFormat("0.##").format(size * 1.0 / (1024 * 1024));
        //DecimalFormat用于十进制数字格式化，0.##小数点后保留两位
    }

    public static String getTime(long millis) {//格式化日期
        Date date = new Date(millis);
        //SimpleDateFormat格式日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    public static boolean openPackage(Context context,String packageName){//打开新应用
        try{
            //获得需要启动软件的intent
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
            if(intent != null){
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//在新的进程中打开
                context.startActivity(intent);
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
/*    public static void openPackage(Context context,String packageName){
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//在新的进程中打开
        context.startActivity(intent);
    }*/
    public static void uninstallApp(Activity context, String packageName, int requestCode){//应用卸载
/*        Uri uri = Uri.parse("package"+packageName);//解析得到包安装地址
        Intent intent = new Intent(Intent.ACTION_DELETE,uri);//封装卸载intent
        context.startActivityForResult(intent,requestCode);*/
        Uri uri = Uri.parse("package:"+packageName);//解析得到包安装地址
        Intent intent = new Intent(Intent.ACTION_DELETE,uri);//封装卸载intent
        context.startActivityForResult(intent,requestCode);
    }

    public static List<AppInfo> getSearchResult(List<AppInfo> list,String key){//app查找
        //list查找的集合
        //key查找关键字
        List<AppInfo> result = new ArrayList<AppInfo>();//定义结果集
        for (int i = 0; i < list.size(); i++) {
            AppInfo app = list.get(i);
            if(app.appName.toLowerCase().contains(key.toLowerCase())){
                //contains是否包含关键字
                //contains大小写敏感,通过toLowerCase()转换为小写来比较
                result.add(app);//符合结果添加的结果集
            }
        }
        return result;
    }

    public static SpannableStringBuilder sortHighLight(String str,String key){//设置搜索高亮
        int start = str.toLowerCase().indexOf(key.toLowerCase());
        //indexOf()大小写敏感
        int end = start + key.length();
        SpannableStringBuilder sb = new SpannableStringBuilder(str);
        sb.setSpan(
                new ForegroundColorSpan(Color.RED),
                start,
                end,
                Spannable.SPAN_EXCLUSIVE_INCLUSIVE
        );
        return sb;
    }
}
